package com.example.expresshelp.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

/*
 * HttpClient帮助�?
 */
public class HttpClientHelper {
	private static final String TAG = "HttpClientHelper";
	private static volatile HttpClient httpClient;
	private static String COOKIE = ""; // 缓存
	public static String getDynamicIpUrl = "http://jwgl.sdju.edu.cn/CheckCode.aspx"; // 得到动�?IP的Url
	public static String getIdentifyingUrl = ""; // 得到验证码的url
	public static String loginUrl = ""; // 登录的Url
	public static String welcomeUrl = ""; // 登录成功的url
	public static String mainUrl = ""; // 主界面的url
	public static String schoolTableUrl = ""; // 学生课表的url
	public static String tempUrl = ""; // url中间生成那串字符
	// private HashMap<Integer,Handler> handlers;

	/**
	 * 初始化HttpClient 对象
	 * 
	 * @return
	 */
	public static void initHttpClient() {
		if (httpClient == null) {
			synchronized (HttpClientHelper.class) {
				if (httpClient == null) {
					// 创建HttpParams来设置Http参数，这�?��分不是必须的
					HttpParams httpParams = new BasicHttpParams();
					// 设置连接超时和Socket超时，以及Socket缓存大小
					HttpConnectionParams.setConnectionTimeout(httpParams,
							90 * 1000);
					HttpConnectionParams.setSoTimeout(httpParams, 90 * 1000);
					// HttpConnectionParams.setSocketBufferSize(httpParams,
					// 200000);
					// 设置重定向，自己处理
					HttpClientParams.setRedirecting(httpParams, false);
					// 设置user agent
					String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
					HttpProtocolParams.setUserAgent(httpParams, userAgent);
					// 创建�?��HttpClient对象
					httpClient = new DefaultHttpClient(httpParams);
				}
			}
		}
	}

	/**
	 * �?��HttpClient对象
	 */
	public static void destoryHttpClient() {
		if (httpClient != null) {
			httpClient = null;
		}
	}

	/**
	 * HttpClient get请求
	 * 
	 * @param url
	 * @param params
	 */
	public static Object doGet(final String url, final Map params, Map headers) {
		String tempUrl = url;
		// TODO Auto-generated method stub
		// 构建HttpGet对象
		String paramStr = "";
		if (params != null) {
			Iterator iter = params.entrySet().iterator();
			while (iter.hasNext()) {
				Entry entry = (Entry) iter.next();
				Object key = entry.getKey();
				Object value = entry.getValue();
				paramStr = paramStr + ("&" + key + "=" + value);
			}
			if (!paramStr.equals("")) {
				paramStr = paramStr.replaceFirst("&", "?");
				tempUrl = tempUrl + paramStr;
			}
		}
		HttpGet httpGet = new HttpGet(tempUrl);
		try {
			// 发�?请求
			if (COOKIE != null && !COOKIE.equals("")) {
				httpGet.setHeader("Cookie", "igufjcxf=" + COOKIE);
			}
			if (headers != null) {
				String refererString = (String) headers.get("Referer");
				if (refererString != null) {
					Log.v(TAG, "referer-->" + refererString);
					httpGet.setHeader("Referer", refererString);
				}
				String accept = (String) headers.get("Accept");
				if (accept != null) {
					Log.v(TAG, "Accept-->" + accept);
					httpGet.setHeader("Accept", accept);
				}
				String acceptEncoding = (String) headers.get("Accept-Encoding");
				if (acceptEncoding != null) {
					Log.v(TAG, "acceptEncoding-->" + acceptEncoding);
					httpGet.setHeader("Accept-Encoding", acceptEncoding);
				}
				String dnt = (String) headers.get("DNT");
				if (dnt != null) {
					Log.v(TAG, "dnt-->" + dnt);
					httpGet.setHeader("DNT", dnt);
				}
				String host = (String) headers.get("Host");
				if (host != null) {
					Log.v(TAG, "Host-->" + host);
					httpGet.setHeader("Host", host);
				}
			}
			HttpResponse httpResponse = httpClient.execute(httpGet);
			int responseCode = httpResponse.getStatusLine().getStatusCode();
			if (COOKIE == null || COOKIE.equals("")) {
				COOKIE = ((AbstractHttpClient) httpClient).getCookieStore()
						.getCookies().get(0).getValue();
			}

			if (responseCode == 302) { // 转发
				Log.v(TAG, "doGet 302");
				Header locationHeader = httpResponse.getFirstHeader("Location");
				if (locationHeader != null) {
					String locationUrl = locationHeader.getValue();
					Log.v(TAG, "get location url-->" + locationUrl);
					HttpClientHelper.tempUrl = locationUrl.substring(0,
							locationUrl.indexOf(")") + 2);
					return locationUrl;
				}
			} else if (responseCode == 200) { // 请求成功
				Log.v(TAG, "doGet 200");
				HttpEntity httpEntity = httpResponse.getEntity();
				return httpEntity;
			} else {

			}
		} catch (Exception e) {
		}
		return null;

	}

	/**
	 * HttpClient Post方式
	 */
	public static String doPost(final String url,
			final List<NameValuePair> params, final int actionType) {
		// 建立HttpPost对象
		initHttpClient();
		HttpPost httpPost = new HttpPost(url);
		try {
			httpPost.setHeader("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
			HttpResponse httpResponse = httpClient.execute(httpPost);
			int responseCode = httpResponse.getStatusLine().getStatusCode();
			Log.v(TAG, "post code - >" + responseCode);
			if (responseCode == 200) {
				Log.v(TAG, "do post 200");
				HttpEntity httpEntity = httpResponse.getEntity();
				InputStream is = httpEntity.getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is, "gb2312"));
				StringBuffer sb = new StringBuffer();
				String data = new String();
				while ((data = br.readLine()) != null) {
					sb.append(data);
				}
				String result = sb.toString();
				return result;
			} else {

			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/**
	 * HttpClient异步任务
	 */
	public static class HttpClientAsyncTask extends AsyncTask<Void, Void, Void> {

		private Map data;

		public HttpClientAsyncTask(Map data) {
			this.data = data;
		}

		@Override
		protected Void doInBackground(Void... params) {
			Object result = null;
			if (data != null) {
				// 操作类型
				int actionType = (Integer) data.get("actionType");
				// 根据操作类型分类
				switch (actionType) {

				default:
					break;
				}

			}
			return null;
		}

	}

	/**
	 * 得到动�?IP,Get方式，得到Url中间那串动�?生成的字�?
	 * 
	 * @return
	 */
	public static String getDynamicIp() {
		String locationUrl = (String) doGet(HttpClientHelper.getDynamicIpUrl,
				null, null);
		return locationUrl;
	}

	/**
	 * 得到验证码（图片格式），Get方式
	 * 
	 * @return 验证码图�?
	 */
	public static Bitmap getIdentifyingCode() {
		HttpEntity httpEntity = (HttpEntity) doGet(
				HttpClientHelper.getIdentifyingUrl, null, null);
		byte[] bytes;
		// TODO Auto-generated method stub
		try {
			bytes = EntityUtils.toByteArray(httpEntity);
			Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
					bytes.length);
			return bitmap;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 模拟登陆，post 方式
	 * 
	 * @return 登陆成功，则返回302，重定向，返回重定向的locationUrl
	 */
	/*
	 * public static String login(List<NameValuePair> params) { return
	 * locationUrl; }
	 */
	/**
	 * 模拟登陆成功以后，读取欢迎界面，Get方式
	 * 
	 * @return 欢迎界面的html字符�?
	 */
	private static String goWelcome() {
		HttpEntity httpEntity = (HttpEntity) doGet(HttpClientHelper.welcomeUrl,
				null, null);
		try {
			InputStream is = httpEntity.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"gbk"));
			StringBuffer sb = new StringBuffer();
			String data = new String();
			while ((data = br.readLine()) != null) {
				sb.append(data);
			}
			String result = sb.toString();
			if (result != null && !result.equals("")) {
				Log.v(TAG, "登录成功，登陆结�?->" + result);
			} else {
				Log.v(TAG, "登陆失败");
			}
			return result;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/**
	 * 登陆成功以后，得到主页的详细信息,Get方式
	 * 
	 * @return 主页详细信息html的字符串
	 */
	private static String getMainContent() {
		// 构建参数
		HttpEntity httpEntity = (HttpEntity) doGet(HttpClientHelper.mainUrl,
				null, null);
		try {
			InputStream is = httpEntity.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"gbk"));
			StringBuffer sb = new StringBuffer();
			String data = new String();
			while ((data = br.readLine()) != null) {
				sb.append(data);
			}
			String result = sb.toString();
			if (result != null && !result.equals("")) {
				Log.v(TAG, "登录成功，主界面-->" + result);
			} else {
				Log.v(TAG, "登陆失败");
			}
			return result;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/**
	 * 得到学校课表,Get方式
	 * 
	 * @return
	 */
	private static String getShchoolTable(String xh, String name) {
		String getShchoolTable = "http://jwgl.sdju.edu.cn" + tempUrl
				+ "xskbcx.aspx?xh=" + xh + "&xm=" + name + "&gnmkdm=N121603";
		Log.v(TAG, "getshchoolUrl-->" + getShchoolTable);
		// 设置头信�?
		Map headers = new HashMap();
		headers.put("Referer", "http://jwgl.sdju.edu.cn/" + tempUrl
				+ "/xs_main.aspx?xh=111003610137");
		headers.put("Accept", "text/html, application/xhtml+xml, */*");
		headers.put("Accept-Encoding", "gzip, deflate");
		headers.put("DNT", "1");
		headers.put("Host", "jwgl.sdju.edu.cn");
		HttpEntity httpEntity = (HttpEntity) doGet(getShchoolTable, null,
				headers);
		try {
			InputStream is = httpEntity.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"gbk"));
			StringBuffer sb = new StringBuffer();
			String data = new String();
			while ((data = br.readLine()) != null) {
				sb.append(data);
			}
			String result = sb.toString();
			if (result != null && !result.equals("")) {
				Log.v(TAG, "得到课表成功，主界面-->" + result);
			} else {
				Log.v(TAG, "得到课表失败");
			}
			return result;
		} catch (Exception e) {
			// TODO: handle exception
		}

		return null;
	}
}
